package com.shopping_back.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.OrderBuyNowDTO;
import com.shopping_back.pojo.dto.OrderDTO;
import com.shopping_back.service.IOrderMainService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 主订单表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@RestController
@RequestMapping("/api/order-main")
@RequiredArgsConstructor
public class OrderMainController {

    private final IOrderMainService orderMainService;

    private final JwtUtils jwtUtils;

    @GetMapping
    public Result getOrders(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        Page<OrderDTO> orderDTOPage = orderMainService.getOrders(userId, page, size);
        Map<String, Object> response = new HashMap<>();
        response.put("code", "200");
        response.put("data", orderDTOPage);
        response.put("message", null);
        return Result.success(response);
    }

    @PostMapping("/add")
    public Result addOrder(@RequestBody OrderBuyNowDTO dto, HttpServletRequest request) {
        // 从token解析userId
        Long userId = jwtUtils.getCurrentUserId(request);
        System.out.println(dto.toString());
        return Result.success(orderMainService.buyNow(dto, userId));
    }

    @PostMapping("/pay")
    public Result payOrder(@RequestParam("orderId") Long orderId) {
        try {
            orderMainService.payOrder(orderId);
            return Result.success(null, "支付成功");
        } catch (Exception e) {
            return Result.error("支付失败: " + e.getMessage());
        }
    }

    @PostMapping("/cancel")
    public Result cancelOrder(@RequestParam("orderId") Long orderId) {
        try {
            orderMainService.cancelOrder(orderId);
            return Result.success(null, "取消成功");
        } catch (Exception e) {
            return Result.error("取消订单失败: " + e.getMessage());
        }
    }

    @PostMapping("/refund")
    public Result refundOrder(@RequestParam("orderId") Long orderId) {
        try {
            orderMainService.refundOrder(orderId);
            return Result.success(null, "退款申请成功");
        } catch (Exception e) {
            return Result.error("退款申请失败: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    public Result deleteOrder(@RequestParam("orderId") Long orderId) {
        try {
            orderMainService.deleteOrder(orderId);
            return Result.success(null, "删除成功");
        } catch (Exception e) {
            return Result.error("删除订单失败: " + e.getMessage());
        }
    }
}
